package system.task.logger.buffer;

import lombok.Getter;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class TaskLogBuffer {

    private final int maxLine;
    private final AtomicInteger counter = new AtomicInteger();
    private final Queue<TaskLogBufferItem> queue = new ConcurrentLinkedQueue<>();
    @Getter
    private String name;


    public TaskLogBuffer(int maxLine, String name) {
        this.maxLine = maxLine;
        this.name = name;
    }

    /**
     * 获取一个列表
     *
     * @param lastIndex
     * @return
     */
    public List<TaskLogBufferItem> list(int lastIndex) {
        List<TaskLogBufferItem> list = new ArrayList<>();
        for (TaskLogBufferItem item : this.queue) {
            if (lastIndex - item.getIndex() < 0) {
                list.add(item);
            }
        }
        return list;
    }

    public void log(String runId, String message) {
        this.queue.add(new TaskLogBufferItem(this.counter.incrementAndGet(), runId, message));
        if (this.queue.size() > this.maxLine) {
            synchronized (this.queue) {
                while (this.queue.size() > this.maxLine) {
                    this.queue.poll();
                }
            }
        }
    }

}
